package com.fms.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fms.entity.VersionInstaller;
import com.fms.exception.ServiceException;
import com.fms.mapper.VersionInstallerMapper;
import com.fms.result.ResultData;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/version")
@RequiredArgsConstructor
public class VersionController {

    private final VersionInstallerMapper versionInstallerMapper;
    @PostMapping("/upload")
    @PreAuthorize("hasRole('管理员')")
    public ResultData versionUpload(@RequestBody VersionInstaller versionInstaller) {
        String version = versionInstaller.getVersion();
        //存入数据库
        try{
            versionInstallerMapper.insert(versionInstaller);
        }catch (Exception e){
            throw new ServiceException("上传"+version+"版本安装包失败,可能version或url已存在");
        }
        return ResultData.success("上传."+version+"版本安装包成功");
    }

    @GetMapping("/download/{version}")
    public ResultData versionDownload(@PathVariable String version) {
        VersionInstaller versionInstaller = versionInstallerMapper
                .selectOne(new LambdaQueryWrapper<VersionInstaller>()
                        .eq(VersionInstaller::getVersion, version));
        if(versionInstaller==null){
            throw new ServiceException("未找到版本安装包");
        }else{
            return ResultData.success("获取"+version+"版本安装包成功",versionInstaller);
        }
    }

    @GetMapping("/list")
    public ResultData versionList() {
        return ResultData.success(versionInstallerMapper.selectList(new LambdaQueryWrapper<VersionInstaller>()
                .orderBy(true, false, VersionInstaller::getCreateDate)));
    }
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasRole('管理员')")
    public ResultData versionDelete(@PathVariable Long id) {
        if(versionInstallerMapper.deleteById(id)==0){
            throw new ServiceException("删除版本安装包失败");
        }else{
            return ResultData.success("删除版本安装包成功");
        }
    }

    @PutMapping("/update")
    @PreAuthorize("hasRole('管理员')")
    public ResultData versionUpdate(@RequestBody VersionInstaller versionInstaller) {
        try {
            versionInstallerMapper.updateById(versionInstaller);
        }catch (Exception e){
            throw new ServiceException("更新版本安装包失败，可能version或url已存在");
        }
        return ResultData.success("更新版本安装包成功");
    }
}
